package org.jeecg.modules.flower.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.UpdateById;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.service.*;
import org.jeecg.modules.flower.util.CommonUtil;
import org.jeecg.modules.flower.vo.TFlowerTagInMain2Page2;
import org.jeecg.modules.flowerutil.PeriodUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.def.TemplateExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.flower.vo.TFlowerTagInMain2Page;
import org.jeecgframework.poi.excel.view.JeecgTemplateExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 批量入库表主表
 * @Author: jeecg-boot
 * @Date: 2022-07-22
 * @Version: V1.0
 */
@Api(tags = "批量入库表主表")
@RestController
@RequestMapping("/flower/tFlowerTagInMain2")
@Slf4j
public class TFlowerTagInMain2Controller {
    @Autowired
    private ITFlowerTagInMain2Service tFlowerTagInMain2Service;
    @Autowired
    private ITFlowerTagIn2Service tFlowerTagIn2Service;
    @Autowired
    private IFlowerStorehouseService flowerStorehouseService;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private IFlowerPlantingGreenhouseService greenhouseService;
    @Autowired
    private IFlowerSettleAccountsService settleAccountsService;
    @Autowired
    private ISysUserService sysUserService;
    @Value("${yth.tempExcelin}")
    private String tempExcelin;


    /**
     * 分页列表查询
     *
     * @param tFlowerTagInMain2
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "批量入库表主表-分页列表查询")
    @ApiOperation(value = "批量入库表主表-分页列表查询", notes = "批量入库表主表-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent = "flower/TFlowerTagInMain2List")
    public Result<?> queryPageList(TFlowerTagInMain2 tFlowerTagInMain2,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(value = "sDate", defaultValue = "") String sDate,
                                   @RequestParam(value = "eDate", defaultValue = "") String eDate,
                                   HttpServletRequest req) {
        QueryWrapper<TFlowerTagInMain2> queryWrapper = QueryGenerator.initQueryWrapper(tFlowerTagInMain2, req.getParameterMap());
        Page<TFlowerTagInMain2> page = new Page<TFlowerTagInMain2>(pageNo, pageSize);
        queryWrapper.orderByDesc("sort_time");
        queryWrapper.orderByDesc("create_time");
        if (StringUtils.isNotBlank(sDate)) {
            queryWrapper.ge("sort_time", sDate);
        }
        if (StringUtils.isNotBlank(eDate)) {
            queryWrapper.le("sort_time", eDate + " 23:59:59");
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        queryWrapper.inSql("storehouse", "SELECT b.code  FROM flower_storehouse b LEFT JOIN flower_storehouse_detail c   on  b.id = c.mainid where c.personid = '" + sysUser.getId() + "'");

        QueryGenerator.installAuthMplus(queryWrapper, TFlowerTagInMain2.class);

        IPage<TFlowerTagInMain2> pageList = tFlowerTagInMain2Service.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param tFlowerTagInMain2Page
     * @return
     */
    @AutoLog(value = "批量入库表主表-添加")
    @ApiOperation(value = "批量入库表主表-添加", notes = "批量入库表主表-添加")
    @PostMapping(value = "/add")
    public synchronized Result<?> add(@RequestBody TFlowerTagInMain2Page tFlowerTagInMain2Page) {
        TFlowerTagInMain2 tFlowerTagInMain2 = new TFlowerTagInMain2();
        BeanUtils.copyProperties(tFlowerTagInMain2Page, tFlowerTagInMain2);
        tFlowerTagInMain2Service.saveMain(tFlowerTagInMain2, tFlowerTagInMain2Page.getTFlowerTagIn2List());
        return Result.ok("添加成功！");
    }

    /**
     * PDA添加
     *
     * @param tFlowerTagInMain2Page
     * @return
     */
    @AutoLog(value = "批量入库表主表-PDA添加")
    @ApiOperation(value = "批量入库表主表-PDA添加", notes = "批量入库表主表-PDA添加")
    @PostMapping(value = "/add2")
    public synchronized Result<?> add22(@RequestBody TFlowerTagInMain2Page2 tFlowerTagInMain2Page) {
        TFlowerTagInMain2 tFlowerTagInMain2 = new TFlowerTagInMain2();
        String variety = tFlowerTagInMain2Page.getVariety();
//        JSONArray list = JSONArray.parseArray(variety);

        List<TFlowerTagIn2> list1 = JSONObject.parseArray(variety, TFlowerTagIn2.class);

//        JSONObject jsonObject1 = list.getJSONObject(0);
//        TFlowerTagIn2 flowerTagIn2  = JSONObject.toJavaObject(jsonObject1,TFlowerTagIn2.class);
        tFlowerTagInMain2Page.setVariety("");
        BeanUtils.copyProperties(tFlowerTagInMain2Page, tFlowerTagInMain2);
        tFlowerTagInMain2Service.saveMain2(tFlowerTagInMain2, list1);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param tFlowerTagInMain2Page
     * @return
     */
    @AutoLog(value = "批量入库表主表-编辑")
    @ApiOperation(value = "批量入库表主表-编辑", notes = "批量入库表主表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody TFlowerTagInMain2Page tFlowerTagInMain2Page) {
        TFlowerTagInMain2 tFlowerTagInMain2 = new TFlowerTagInMain2();
        BeanUtils.copyProperties(tFlowerTagInMain2Page, tFlowerTagInMain2);
        Integer state = tFlowerTagInMain2.getState();
        if (state != 0) {
            throw new RuntimeException("已审核的单据不可编辑！");
        }
        TFlowerTagInMain2 tFlowerTagInMain2Entity = tFlowerTagInMain2Service.getById(tFlowerTagInMain2.getId());
        if (tFlowerTagInMain2Entity == null) {
            return Result.error("未找到对应数据");
        }
        boolean accountState = settleAccountsService.getAccountState(tFlowerTagInMain2Page.getPeriod());
        if (!accountState) {
            throw new RuntimeException("已结账的单据不可编辑！");
        }
        synchronized (tFlowerTagInMain2.getId()) {
            tFlowerTagInMain2Service.updateMain(tFlowerTagInMain2, tFlowerTagInMain2Page.getTFlowerTagIn2List());
        }
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "批量入库表主表-通过id删除")
    @ApiOperation(value = "批量入库表主表-通过id删除", notes = "批量入库表主表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        tFlowerTagInMain2Service.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "批量入库表主表-批量删除")
    @ApiOperation(value = "批量入库表主表-批量删除", notes = "批量入库表主表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.tFlowerTagInMain2Service.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "批量入库表主表-通过id查询")
    @ApiOperation(value = "批量入库表主表-通过id查询", notes = "批量入库表主表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        TFlowerTagInMain2 tFlowerTagInMain2 = tFlowerTagInMain2Service.getById(id);
        if (tFlowerTagInMain2 == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(tFlowerTagInMain2);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "入库子表通过主表ID查询")
    @ApiOperation(value = "入库子表主表ID查询", notes = "入库子表-通主表ID查询")
    @GetMapping(value = "/queryTFlowerTagIn2ByMainId")
    public Result<?> queryTFlowerTagIn2ListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<TFlowerTagIn2> tFlowerTagIn2List = tFlowerTagIn2Service.selectByMainId(id);
        return Result.ok(tFlowerTagIn2List);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param tFlowerTagInMain2
     */
    @RequestMapping(value = "/exportXls")
    @PermissionData(pageComponent = "flower/TFlowerTagInMain2List")
    public ModelAndView exportXls(HttpServletRequest request, TFlowerTagInMain2 tFlowerTagInMain2,
                                  @RequestParam(value = "sDate", defaultValue = "") String sDate,
                                  @RequestParam(value = "eDate", defaultValue = "") String eDate) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<TFlowerTagInMain2> queryWrapper = QueryGenerator.initQueryWrapper(tFlowerTagInMain2, request.getParameterMap());
        queryWrapper.orderByAsc("sort_time");
        queryWrapper.orderByAsc("create_time");
        if (StringUtils.isNotBlank(sDate)) {
            queryWrapper.ge("sort_time", sDate);
        }
        if (StringUtils.isNotBlank(eDate)) {
            queryWrapper.le("sort_time", eDate + " 23:59:59");
        }

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        queryWrapper.inSql("storehouse", "SELECT b.code  FROM flower_storehouse b LEFT JOIN flower_storehouse_detail c  on  b.id = c.mainid where c.personid = '" + sysUser.getId() + "'");
        QueryGenerator.installAuthMplus(queryWrapper, TFlowerTagInMain2.class);
        //Step.2 获取导出数据
        List<TFlowerTagInMain2> queryList = tFlowerTagInMain2Service.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<TFlowerTagInMain2> tFlowerTagInMain2List = new ArrayList<TFlowerTagInMain2>();
        if (oConvertUtils.isEmpty(selections)) {
            tFlowerTagInMain2List = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            tFlowerTagInMain2List = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<TFlowerTagInMain2Page> pageList = new ArrayList<TFlowerTagInMain2Page>();
        for (TFlowerTagInMain2 main : tFlowerTagInMain2List) {
            TFlowerTagInMain2Page vo = new TFlowerTagInMain2Page();
            BeanUtils.copyProperties(main, vo);
            List<TFlowerTagIn2> tFlowerTagIn2List = tFlowerTagIn2Service.selectByMainId(main.getId());
            vo.setTFlowerTagIn2List(tFlowerTagIn2List);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "批量入库表主表列表");
        mv.addObject(NormalExcelConstants.CLASS, TFlowerTagInMain2Page.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("批量入库表主表数据", "导出人:" + sysUser.getRealname(), "批量入库表主表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<TFlowerTagInMain2Page> list = ExcelImportUtil.importExcel(file.getInputStream(), TFlowerTagInMain2Page.class, params);
                for (TFlowerTagInMain2Page page : list) {
                    TFlowerTagInMain2 po = new TFlowerTagInMain2();
                    BeanUtils.copyProperties(page, po);
                    tFlowerTagInMain2Service.saveMain(po, page.getTFlowerTagIn2List());
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /**
     * 导出excel入库单
     *
     * @param request
     * @param tFlowerTagInMain2
     * @return
     */
    @RequestMapping(value = "/exportXlsForTemp")
    @ApiOperation(value = "导出excel入库单-导出excel入库单", notes = "导出excel入库单-导出excel入库单")
    public ModelAndView exportXlsForTemp(HttpServletRequest request, TFlowerTagInMain2 tFlowerTagInMain2) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        if (StringUtils.isBlank(tempExcelin)) {
            throw new RuntimeException("还未配置入库单模板，请联系管理员配置入库单模板");
        }
        TemplateExportParams params = new TemplateExportParams(tempExcelin);//模板

        String id = tFlowerTagInMain2.getId();
        TFlowerTagInMain2 tagInMain2 = tFlowerTagInMain2Service.getById(id);

        String cost = tagInMain2.getCost();
        String storehouse2 = tagInMain2.getStorehouse();
        String storehouseName = "";
        String costName = "";
        if (StringUtils.isBlank(cost) || StringUtils.isBlank(storehouse2)) {
            throw new RuntimeException("历史数据不可以导出入库单");
        } else {
            QueryWrapper<FlowerStorehouse> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("code", storehouse2);
            FlowerStorehouse house = flowerStorehouseService.getOne(queryWrapper2);
            storehouseName = house.getName();

            String name = sysDictService.queryDictTextByKey("ch_cost", cost);
            costName = name;
        }
        String no = "";
        if (StringUtils.isNotBlank(tagInMain2.getNo())) {
            no = tagInMain2.getNo();
        }
        String sourceGreenhouse = "";
        if (StringUtils.isNotBlank(tagInMain2.getSourceGreenhouse())) {
            FlowerPlantingGreenhouse greenhouse = greenhouseService.getById(tagInMain2.getSourceGreenhouse());
            sourceGreenhouse = greenhouse.getName();
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sortTime", simpleDateFormat.format(tagInMain2.getSortTime()));
        map.put("cost", tagInMain2.getProductionId());
        map.put("no", no);
        SysUser user = sysUserService.getUserByName(tagInMain2.getCreateBy());
        map.put("createBy", user.getRealname());
        map.put("baseCadre", tagInMain2.getBaseCadre());
        List<TFlowerTagIn2> tFlowerTagIn2s = tFlowerTagIn2Service.selectByMainId(id);

        if (tFlowerTagIn2s.size() == 0) {
            throw new RuntimeException("没有入库详情不能生成入库单");
        }
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
        BigDecimal countPrice = BigDecimal.ZERO;
        BigDecimal countNum = BigDecimal.ZERO;
        int i = 1;
        for (TFlowerTagIn2 flowerTagIn2 : tFlowerTagIn2s) {
            Map<String, Object> lm = new HashMap<String, Object>();

            lm.put("no", i);
            i++;
            lm.put("storehouse", storehouseName);
            lm.put("sourceGreenhouse", sourceGreenhouse);
            lm.put("variety", flowerTagIn2.getVariety());
            lm.put("claess", flowerTagIn2.getClasses());

            lm.put("packingSpecifications", flowerTagIn2.getPackingSpecifications());
            lm.put("flowerPoleLength", flowerTagIn2.getFlowerPoleLength());
            lm.put("number", flowerTagIn2.getTagNum());
            countNum = countNum.add(flowerTagIn2.getTagNum());//计算数量合计

            listMap.add(lm);
        }
        if (tFlowerTagIn2s.size() == 1) {
            Map<String, Object> lm = new HashMap<String, Object>();
            listMap.add(lm);
        }
        map.put("sumNumber", countNum);
        map.put("maplist", listMap);

        ModelAndView mv2 = new ModelAndView(new JeecgTemplateExcelView());
        mv2.addObject(TemplateExcelConstants.PARAMS, params);
        mv2.addObject(TemplateExcelConstants.MAP_DATA, map);
        return mv2;
    }

    @AutoLog(value = "批量入库表主表-审核确认入库")
    @ApiOperation(value = "批量入库表主表-审核确认入库", notes = "批量入库表主表-审核确认入库")
    @GetMapping(value = "/sure")
    public Result<?> sure(@RequestParam("id") String id) {
        synchronized (CommonUtil.SUBTAGINFOKEY) {
            tFlowerTagInMain2Service.sure(id);
        }
        return Result.ok("入库成功");
    }

    @AutoLog(value = "批量入库表主表-审核确认入库--撤销")
    @ApiOperation(value = "批量入库表主表-审核确认入库--撤销", notes = "批量入库表主表-审核确认入库--撤销")
    @GetMapping(value = "/sureBack")
    public Result<?> sureBack(@RequestParam("id") String id) {
        synchronized (CommonUtil.SUBTAGINFOKEY) {
            tFlowerTagInMain2Service.sureBack(id);
        }
        return Result.ok("撤销审核成功");
    }
}
